<?php

namespace backend\controllers;

use backend\models\file\AttExtend;
use backend\models\file\AttSchoolFiles;
use backend\models\form\FormProject;
use backend\models\form\FormProjectBasicInfo;
use backend\utils\AppUtil;
use backend\models\form\FormProjectMajorBasis;
use backend\models\form\FormProjectMajorBasisExt;
use backend\utils\FileUpUtil;
use backend\utils\NBFile;
use Yii;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

class FormController extends BaseController
{
    //-------------------- 前端添加yii2验证 表单 START --------------------------------------------------------

    /**
     * @desc form/basic-info2
     * @return string|\yii\web\Response
     * @Date: 2024/10/31
     */
    public function actionBasicInfo2()
    {
        $project_basic_info_id = Yii::$app->request->get('project_basic_info_id');
        // 模拟的专业数据
        $majors = [
            '01011' => '软件工程技术',
            '01012' => '智能制造工程技术',
            '01013' => '新能源汽车工程技术',
            '01014' => '船舶智能制造技术',
            '01015' => '航空智能制造技术',
        ];

        $model1 = FormProjectBasicInfo::findOne($project_basic_info_id);
        if (!$model1) {
            $model1 = new FormProjectBasicInfo();
            $model1->uuid = AppUtil::init_uuid();
            $model1->batch_id = 1;
            $model1->department_id = 'department_id';
            $model1->status = 1;
            $model1->create_time = AppUtil::get_format_time();
            $model1->update_time = AppUtil::get_format_time();
            $model1->create_users_id = 'user_id_test';
            $model1->update_users_id = 'user_id_test';
        }

        $model2 = FormProjectMajorBasis::findOne([
            'project_basic_info_id' => $project_basic_info_id,
            'status' => 1,
        ]);
        if (!$model2) {
            $model2 = new FormProjectMajorBasis();

            $model2->uuid = AppUtil::init_uuid();
            $model2->project_basic_info_id = $model1->uuid;
            $model2->status = 1;
            $model2->create_time = AppUtil::get_format_time();
            $model2->update_time = AppUtil::get_format_time();
            $model2->create_users_id = 'user_id_test';
            $model2->update_users_id = 'user_id_test';
        }

        $postData = Yii::$app->request->post();

        $transaction = Yii::$app->db->beginTransaction();
        if ($postData) {
            $data_post_groups = $postData['post_group'];

            $model1->load($postData);
            $model2->load($postData);

            $model1->main_industry = implode(",", $postData[$model1->formName()]['main_industry']); // 主要面向产业
            $model1->post_group = implode(",", $data_post_groups); // 面向的职业岗位

            $insert = $postData['tableName'] ?? [];
            FormProjectMajorBasisExt::deleteAll(['project_basic_info_id' => $model1->uuid]);

            $flag = 1;
            $err_msg = "";
            if ($insert) {
                foreach ($insert as $k => $v) {
                    $model3 = new FormProjectMajorBasisExt();
                    $major_code = $v['field2'];
                    $model3->setAttributes([
                        'uuid' => AppUtil::init_uuid(),
                        'project_basic_info_id' => $model1->uuid,
                        'major_code' => $major_code,
                        'major_name' => $majors[$major_code] ?? 'major_name_default',
                        'major_open_date' => $v['field3'],
                        'student_number' => $v['field4'],
                        'employment_rate' => $v['field5'],
                        'status' => 1,
                        'px' => $k + 1,
                        'create_time' => AppUtil::get_format_time(),
                        'update_time' => AppUtil::get_format_time(),
                        'create_users_id' => 'user_id_test',
                        'update_users_id' => 'user_id_test',
                    ]);
                    $res3 = $model3->save();
                    if (!$res3) {
                        $flag = false;
                        $err_msg = AppUtil::get_error_msg($model3);
                        break;
                    }
                }
            }

            try {
                if ($model1->save() && $model2->save() && $flag) {
                    $transaction->commit();
                    return $this->redirect(['basic-info2',
                        'project_basic_info_id' => $model1->uuid,
                    ]);
                } else {
                    $err_msg = AppUtil::get_error_msg($model1) . ' | ' . AppUtil::get_error_msg($model2) . ' | ' . $err_msg;
                    throw new \Exception($err_msg);
                }
            } catch (\Exception $exc) {
                $transaction->rollBack();
                throw new \Exception($exc->getMessage());
            }
        }

        $exts = FormProjectMajorBasisExt::get_major_arr($project_basic_info_id);
        $model1->main_industry = explode(",", $model1->main_industry); // 主要面向产业

        return $this->render('form21_basic_info2', [
            'model1' => $model1,
            'project_basic_info_id' => $model1->uuid,
            'model2' => $model2,
            'exts' => $exts,
            'majors' => $majors,
        ]);
    }

    public function actionValidate211()
    {
        $model1 = new FormProjectBasicInfo();
        $model2 = new FormProjectMajorBasis();

        $request = Yii::$app->getRequest();

        $post = $request->post();

        $form_name = $model1->formName();
        $main_industry = $post[$form_name]['main_industry'];
        $post[$form_name]['main_industry'] = $main_industry
            ? implode(",", $main_industry)
            : ''; // 主要面向产业

        if ($request->isAjax && $model1->load($post) && $model2->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return array_merge(ActiveForm::validate($model1), ActiveForm::validate($model2));
        }
    }

    //-------------------- 前端添加yii2验证 表单 END --------------------------------------------------------

    //-------------------- 弹框上传文件 START --------------------------------------------------------

    /**
     * @desc 弹框上传文件
     * @return string
     * @Date: 2024/11/1
     */
    public function actionUpFileAlert()
    {
        return $this->render('up_file_alert', [
            'file_word' => AttSchoolFiles::get_file_by_type(AttSchoolFiles::TYPE_WORD),
            'file_pdf' => AttSchoolFiles::get_file_by_type(AttSchoolFiles::TYPE_PDF),
        ]);
    }

    /**
     * @desc 弹框上传文件 弹框
     * @return string
     * @Date: 2024/11/1
     */
    public function actionUpFileAlertView()
    {
        $type = Yii::$app->request->post('type');

        return $this->renderAjax('up_file_alert_view', [
            'model_word' => AttSchoolFiles::get_file_by_type(AttSchoolFiles::TYPE_WORD),
            'model_pdf' => AttSchoolFiles::get_file_by_type(AttSchoolFiles::TYPE_PDF),
        ]);
    }

    /**
     * @desc 弹框上传文件 API
     * @return array
     * @Date: 2024/11/1
     */
    public function actionUpFileAlertSave()
    {
        $file_type = Yii::$app->request->post('file_type');
        $res = 1;
        $can_upload_file_type = ($file_type == 'word') ? ['doc', 'docx'] : ['pdf'];
        $type = $file_type == 'word' ? 1 : 2;

        list($res1, $err_msg1, $data) = NBFile::file_upload('file', $max_size = 30, $can_upload_file_type);

        $file = [];
        if ($res1) {
            $file = $data[0];
            $model = AttSchoolFiles::get_file_by_type($type);

            $trans = AppUtil::db()->beginTransaction();

            $attachment_id = $model ? $model->attachment_id : AppUtil::init_uuid();
            AttExtend::updateAll(['status' => 2], ["main_att_id" => $attachment_id]);//delete old

            $table_field = AttSchoolFiles::get_table_field($type);
            list($res3, $err_msg3) = NBFile::add_att_extend($attachment_id, $file, $table_field);

            $up_data = [];
            if (!$model) {
                $model = new AttSchoolFiles();
                $up_data = [
                    'uuid' => AppUtil::init_uuid(),
                    'attachment_id' => "-",
                    'type' => $type,//'类型:1 审计报告(Word);2 审计报告(PDF);
                    'status' => 1,
                ];
            }
            $up_data = array_merge($up_data, ['attachment_id' => $attachment_id,]);
            $model->setAttributes($up_data);
            $res4 = $model->save();
            $err_msg4 = AppUtil::get_error_msg($model);

            if ($res3 && $res4) {
                $trans->commit();
                $err_msg = "上传成功";
            } else {
                $res = 0;
                $err_msg = $err_msg3 . "|" . $err_msg4;
            }
        } else {
            $res = $res1;
            $err_msg = $err_msg1;
        }

        return AppUtil::renderAPI($res ? AppUtil::CODE_SUCCESS : AppUtil::CODE_FAIL, $err_msg, $file);
    }

    //-------------------- 弹框上传文件 END   --------------------------------------------------------

    //-------------------- 上传文件 START   --------------------------------------------------------
    /**
     * @desc 上传文件
     * @return string|Response
     * @Date: 2024/11/18
     */
    public function actionUpFile()
    {
        $type = AttSchoolFiles::TYPE_FILE_3;
        $model = AttSchoolFiles::get_model_by_type($type);

        if (!$model) {
            $model = new AttSchoolFiles();
            $model->setAttributes([
                'uuid' => AppUtil::init_uuid(),
                'attachment_id' => "-",
                'type' => $type,//'类型:1 审计报告(Word);2 审计报告(PDF);
                'status' => 1,
            ]);
        }

        $postData = Yii::$app->request->post();
        if ($postData) {
            try {
                $model->attachment_id = $postData[$model->formName()]['attachment_id'];
                if (!$model->save()) {
                    throw new \Exception(AppUtil::get_error_msg($model));
                }
                return $this->redirect(['']);
            } catch (\Exception $exc) {
                throw new \Exception($exc->getMessage());
            }
        }

        return $this->render('up_file', [
            'model' => $model,
        ]);
    }

    /**
     * @desc 上传文件 接口
     * @return array
     * @Date: 2024/11/18
     */
    public function actionApiUpload()
    {
        $type = Yii::$app->request->post('type');
        $main_att_id = Yii::$app->request->post('id');

        $trans = AppUtil::db()->beginTransaction();
        if (!$main_att_id) {
            $main_att_id = AppUtil::init_uuid();
        }

        // 先删除旧的
        AttExtend::updateAll(['status' => 2, 'submit_time' => AppUtil::get_format_time()], ['main_att_id' => $main_att_id]);
        $table_field = AttSchoolFiles::get_table_field(AttSchoolFiles::TYPE_FILE_3);
        // 再上传新的
        list($code, $err_msg) = FileUpUtil::file_to_db($type, $main_att_id, $table_field);

        if ($code == FileUpUtil::CODE_SUCCESS) {
            $trans->commit();
        } else {
            $trans->rollBack();
        }
        $file = AttExtend::find()->where(['main_att_id' => $main_att_id, 'status' => 1])->asArray()->one();
        $file = $file ?: [];

        return AppUtil::renderAPI($code, $err_msg, [
            'attr_extend' => $file,
        ]);
    }


    //-------------------- 上传文件 END   --------------------------------------------------------

    /**
     * @desc DatePicker 怎么用
     * @return string|Response
     * @Date: 2024/11/4
     */
    public function actionFormProject()
    {
        $project_id = Yii::$app->request->get('project_id', 'project_id_1');
        $model = FormProject::findOne(['uuid' => $project_id, 'status' => AppUtil::STATUS_USE]);
        $attachment_id = (string)$model->attachment_id;

        if (!$model) {
            throw new BadRequestHttpException('The requested page params error.');
        }

        $post = Yii::$app->request->post();
        if ($post) {
            $data = $post[$model->formName()];

            $trans = AppUtil::db()->beginTransaction();
            $attachment_id = $attachment_id ? $attachment_id : AppUtil::init_uuid();
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);

            $model->setAttributes([
                'name' => $data['name'],
                'description' => $data['description'],
                'attachment_id' => $attachment_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'is_achievement' => $data['is_achievement'],
                'progress_status' => $data['progress_status'],
            ]);

            if ($model->save()) {
                $trans->commit();
                return $this->redirect(['form-project', 'project_id' => $model->uuid]);
            } else {
                $trans->rollBack();
                $err_msg = AppUtil::get_error_msg($model);
                $model->addError('uuid', '添加失败:' . $err_msg);
            }
        }

        $model->start_time = $model->start_time ? date('Y-m-d', $model->start_time) : '';
        $model->end_time = $model->end_time ? date('Y-m-d', $model->end_time) : '';

        return $this->render('form_project', [
            'model' => $model,
            'project_name' => $model->name,
        ]);
    }

    public function actionAjaxUnderwayValidate()
    {
        $model = new FormProject();
        $request = Yii::$app->getRequest();

        $post = $request->post();

        if ($request->isPost && $model->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $arr1 = ActiveForm::validate($model);
            //$arr2 = ActiveForm::validate($model2);
            //return array_merge($arr2, $arr1);
            return $arr1;
        }
    }

    public function actionValidateRichText()
    {
        $model = new FormProject();
        $request = Yii::$app->getRequest();

        $post = $request->post();

        if ($request->isPost && $model->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
    }

    /**
     * @desc
     * @return string|Response
     * @Date: 2025/7/10
     */
    public function actionRich_text_create()
    {
        $project_id = Yii::$app->request->get('project_id', '');
        $model = FormProject::findOne(['uuid' => $project_id, 'status' => AppUtil::STATUS_USE]);

        if (!$model) {
            $model = new FormProject();
            $model->setAttributes([
                'uuid' => AppUtil::init_uuid(),
                'status' => AppUtil::STATUS_USE,
                'create_time' => AppUtil::get_format_time(),
                'update_time' => AppUtil::get_format_time(),
                'department_id' => 'Department ID',
                'px' => '123',
                'level' => '123',
                'create_users_id' => 'sys_zp',
                'update_users_id' => 'sys_zp',
            ]);
        }

        $post = Yii::$app->request->post();
        if ($post) {
            $data = $post[$model->formName()];

            $trans = AppUtil::db()->beginTransaction();
            $attachment_id = AppUtil::init_uuid();
            $start_time = time();
            $end_time = time();

            $model->setAttributes([
                'name' => $data['name'],
                'description' => $data['description'],
                'attachment_id' => $attachment_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'is_achievement' => 1,
                'progress_status' => 1,
            ]);

            if ($model->save()) {
                $trans->commit();
                return $this->redirect(['', 'project_id' => $model->uuid]);
            } else {
                $trans->rollBack();
                $err_msg = AppUtil::get_error_msg($model);
//                echo "<pre>";
//                print_r($err_msg);
//                exit;
//                $model->addError('uuid', '添加失败:' . $err_msg);
            }
        }

        return $this->render('rich_text_create', [
            'model' => $model,
        ]);
    }
}
